package com.rlax.framework.plugin.reids.activerecord;

import java.util.Set;

import org.apache.shiro.cache.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.cache.ICache;
import com.jfinal.plugin.redis.Redis;

/**
 * activerecord redis 缓存实现
 * for activerecord 单独使用情况，如果统一管理session，请使用ActiveRecordCache
 * @author Rlax
 *
 */
public class RedisCache implements ICache {

	private final static Logger logger = LoggerFactory.getLogger(RedisCache.class);
	
    public static final String CACHE_KEY = "activerecord_";
	
	@Override
	public <T> T get(String cacheName, Object key) {
		logger.debug("reids cache get key {}_{}", cacheName, key);
        if (key == null) {
            return null;
        } else {
        	return Redis.use().get(CACHE_KEY + cacheName + "_" + key);
        }
	}

	@Override
	public void put(String cacheName, Object key, Object value) {
	  	logger.debug("reids cache put key {}_{}, value {}", new Object[]{cacheName, key, value});
        Redis.use().set(CACHE_KEY + cacheName + "_" + key, value);
	}

	@Override
	public void remove(String cacheName, Object key) {
    	logger.debug("reids cache delete key {}_{}",cacheName, key);
        if (key != null) {
        	Redis.use().del(CACHE_KEY + cacheName + "_" + key);
        }
	}

	@Override
	public void removeAll(String cacheName) {
    	logger.debug("reids cache clear all keys");
        try {
            Set<String> keys = Redis.use().keys(CACHE_KEY + cacheName + "_" + "*");
            Redis.use().del(keys);
        } catch (Throwable t) {
            throw new CacheException(t);
        }
	}

}
